package com.mhkj.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;


import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;

public class ExportExcelUtils {
	/**
	 * 简单的自定义需要导出的数据列
	 * 
	 * @param datas 数据集合
	 * @param title 表格标题(使用英文,连接)
	 * @param key  表格列名(key)(使用英文,连接)
	 * @param name 导出excle的名称(最好不要使用特殊符号)
	 * @param response
	 */
	public void exportData(List<Map<String,Object>> datas,String title,String key,String name,HttpServletResponse response){
		if(StringUtils.isEmpty(key) || StringUtils.isEmpty(title) ){
			return ;
		}
        if(!title.substring(title.length()-1, title.length()).equalsIgnoreCase(",")){
        	title += ",";
		}
        String [] titles = title.split(",");
        
        if(!key.substring(key.length()-1, key.length()).equalsIgnoreCase(",")){
        	key += ",";
		}
        String [] keys = key.split(",");
        
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        for (int i = 0; i < titles.length; i++) {
        	entity.add(new ExcelExportEntity(titles[i], keys[i]));
		}
	    HSSFWorkbook workbook = (HSSFWorkbook) ExcelExportUtil.exportExcel(new ExportParams(name, name), entity, datas);
	    response.setContentType("application/x-download");  
	    //设置导出文件名称  
	    try {
			response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(name, "UTF-8")+".xls");
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass) throws Exception{
        if (StringUtils.isEmpty(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new Exception("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return list;
    }

	public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception{
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);//表格标题行数,默认0
        params.setHeadRows(headerRows);//表头行数,默认1
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new NoSuchElementException("excel文件不能为空");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return list;
    }
	public void downloadExcel(HttpServletResponse response,HttpServletRequest request,String excelPath,String fileName) {
        try {
            //获取文件的路径
        	// excelPath = request.getSession().getServletContext().getRealPath(excelPath);
        	 File path =   new File(ResourceUtils.getURL("classpath:").getPath());  
            // 读到流中
            InputStream inStream = new FileInputStream(path+excelPath);//文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 循环取出流中的数据
            byte[] b = new byte[2048];
            int len;

            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}